package com.koron.css2.clientCenter.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.koron.common.bean.query.SeniorQueryBean;
import com.koron.css2.ServerInterface;
import com.koron.css2.baseConfig.bean.PrefStrategyBean;
import com.koron.css2.baseConfig.mapper.BusinessAreaMapper;
import com.koron.css2.baseConfig.mapper.PrefStrategyMapper;
import com.koron.css2.baseConfig.vo.SelectVO;
import com.koron.css2.clientCenter.bean.AccountInfoBean;
import com.koron.css2.clientCenter.bean.ReadCycleConfigBean;
import com.koron.css2.clientCenter.mapper.AccountInfoMapper;
import com.koron.css2.clientCenter.mapper.UserInfoMapper;
import com.koron.css2.clientCenter.queryBean.UserInfoQueryBean;
import com.koron.css2.clientCenter.vo.UserInfoListVO;
import com.koron.css2.serviceManage.bean.RequestBean;
import com.koron.css2.serviceManage.bean.SelectBean;
import com.koron.css2.serviceManage.bean.UserInfoBean;
import com.koron.css2.serviceManage.utils.JsonUtils;
import com.koron.css2.serviceManage.vo.DictionaryVO;
import com.koron.util.Constant;
import com.koron.util.Tools;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.swan.bean.MessageBean;

import java.time.LocalDate;
import java.util.*;
import java.util.Map.Entry;
import java.util.stream.Collectors;

/**
 * 客户管理接口层
 *
 * @author RealJH
 */
public class UserInfoList implements ServerInterface {

    @Override
    public MessageBean<?> exec(SessionFactory factory, UserInfoBean userInfo, RequestBean req) {
        try {
            MessageBean<PageInfo> info = MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "查询成功", PageInfo.class);
            UserInfoQueryBean uiqBean = JsonUtils.objectToPojo(req.getData(), UserInfoQueryBean.class);
            //判断综合查询list是否存在
            if (uiqBean.getList() != null && uiqBean.getList().size() > 0) {
                Iterator<SeniorQueryBean> it = uiqBean.getList().iterator();
                while (it.hasNext()) {
                    SeniorQueryBean itBean = it.next();
                    if (itBean.getFieldName().equals("stopMonths")) {
                        Integer stopMonths = Integer.valueOf(itBean.getQueryValue());
                        String stopMonthStr = LocalDate.now().minusMonths(stopMonths).toString();
                        uiqBean.setStopMonthStr(stopMonthStr);
                        it.remove();
                    }
                }
            }
            if (uiqBean.getList() != null && uiqBean.getList().size() > 0) {
                uiqBean.setList(concatSql(uiqBean.getList()));
            }
            if (uiqBean.getUseWaterType() != null && uiqBean.getUseWaterType().length > 0) {
                uiqBean.setWaterTypeId(uiqBean.getUseWaterType()[uiqBean.getUseWaterType().length - 1]);
                uiqBean.setWaterTypeLev(uiqBean.getUseWaterType().length);
            }
            UserInfoMapper uiMapper = factory.getMapper(UserInfoMapper.class);

            // 获取客户列表
            //当模糊查询的条件为银行编号时单独处理
            if (uiqBean.getQueryType() == 6 && !StringUtils.isBlank(uiqBean.getFuzzyQuery())) {
                //先去accountInfo表查找
                AccountInfoMapper accountInfoMapper = factory.getMapper(AccountInfoMapper.class);
                AccountInfoBean bean = accountInfoMapper.getAccountByBankNo(uiqBean.getFuzzyQuery());
                //再去调用用户接口
                uiqBean.setQueryType(3);
                uiqBean.setFuzzyQuery(bean==null?null:bean.getAccountNo());
            }
            //当模糊查询的条件为优惠策略时单独处理
            if (uiqBean.getQueryType() == 9 && !StringUtils.isBlank(uiqBean.getFuzzyQuery())) {
                PrefStrategyMapper mapper = factory.getMapper(PrefStrategyMapper.class);
                List<PrefStrategyBean> bean = mapper.selectPrefStrategysByname(uiqBean.getFuzzyQuery());
                if (bean != null && bean.size() > 0) {
                    uiqBean.setPrefStrategyBeans(bean);
                } else {
                    info.setData(new PageInfo(new ArrayList()));
                    return info;
                }
            }
            //营业区域单独处理
            if (uiqBean.getBusinessArea() != null && !"".equals(uiqBean.getBusinessArea())) {
                BusinessAreaMapper mapper = factory.getMapper(BusinessAreaMapper.class);
                List<String> areaIdList = queryChildrenArea(uiqBean.getBusinessArea(), userInfo.getCurWaterCode(), mapper);
                uiqBean.setBusinessAreaList(areaIdList);
            }

            PageHelper.startPage(uiqBean.getPage(), uiqBean.getPageCount());
            List<UserInfoListVO> uiList = uiMapper.userInfoList(uiqBean);


            // 获取用户状态数据字典
            List<DictionaryVO> cusList = Tools.listDicByCode(factory, "CUS");
            //水表分类数据字典
            List<DictionaryVO> meterTypeList = Tools.listDicByCode(factory, "MMT");
            // 获取营业所名称ReaderMRReport
//			List<SelectVO> businessAbodeList = factory.getMapper(BusinessAbodeMapper.class).businessAbodeSelect(userInfo.getCurWaterCode());
            //营业区域
            List<SelectVO> businessAreaList = factory.getMapper(BusinessAreaMapper.class).select(null, userInfo.getCurWaterCode());
            //行业分类
//			List<SelectVO> tradeClassifyList = factory.getMapper(TradeClassifyMapper.class).tradeClassifySelect();
            //用水类型
//			List<WaterTypeVO> waterTypeList = factory.getMapper(WaterTypeMapper.class).findWaterType(null);
            //抄表周期
            List<ReadCycleConfigBean> readCycleConfigList = factory.getMapper(UserInfoMapper.class).readCycleConfigList();
            Map<String, String> readCycleConfigMap = readCycleConfigList.stream().collect(Collectors.toMap(ReadCycleConfigBean::getId, ReadCycleConfigBean::getName));
            //抄表员信息
			/*BaseBookMapper baseBookMapper = factory.getMapper(BaseBookMapper.class);
			baseBookMapper.getMeterReadingStaffName(uiList.stream().map(UserInfoListVO::getM))*/
            for (UserInfoListVO uilVo : uiList) {
                uilVo.setMeterReadingCycleName(readCycleConfigMap.get(uilVo.getMeterReadingCycle()));
                for (DictionaryVO dvo : cusList) {// 根据value获取数据字典名称
                    if ((dvo.getValue() + "").equals(uilVo.getStatus())) {
                        uilVo.setStatus(dvo.getName());
                        break;
                    }
                }
                for (DictionaryVO dvo : meterTypeList) {
                    if ((dvo.getValue() + "").equals(uilVo.getMeterType())) {
                        uilVo.setMeterType(dvo.getName());
                        break;
                    }
                }
/*				for (SelectVO businessAbode : businessAbodeList) {// 获取营业所名称
					if (businessAbode.getId().equals(uilVo.getBusinessAbode())) {
						uilVo.setBusinessAbode(businessAbode.getName());
						break;
					}
				}*/
                for (SelectVO businessArea : businessAreaList) {
                    if (businessArea.getId().equals(uilVo.getBusinessArea())) {
                        uilVo.setBusinessArea(businessArea.getName());
                        break;
                    }
                }
                //抄表员信息

//				for (SelectVO tradeClassify : tradeClassifyList) {
//					if (tradeClassify.getId().equals(uilVo.getTradeClassify())) {
//						uilVo.setTradeClassify(tradeClassify.getName());
//					}
//				}
//				for (WaterTypeVO waterType : waterTypeList) {
//					if (waterType.getId().equals(uilVo.getUseWaterType())) {
//						uilVo.setUseWaterType(waterType.getWaterTypeName());
//						break;
//					}
//				}
				/*if (StringUtils.isNotBlank(uilVo.getMeterReadingCycle())) {
					uilVo.setMeterReadingCycle(Tools.getDicNameByCodeAndValue(factory, "RTP", uilVo.getMeterReadingCycle()));
				}*/
            }

//			PageInfo list = new PageInfo(uiList);
//			if (count !=0){
//				list.setTotal(count);
//			}
            info.setData(new PageInfo(uiList));
            return info;
        } catch (Exception e) {
            logger.error("客户管理列表查询失败" + e.getMessage(), e);
            return MessageBean.create(Constant.MESSAGE_INT_FAIL, "查询失败", null);
        }
    }

    /**
     * 拼接综合查询条件sql
     *
     * @param list
     * @return
     */
    public static List<SeniorQueryBean> concatSql(List<SeniorQueryBean> list) {
        List<SeniorQueryBean> flist = new ArrayList<>();
        //按查询条件分类
        Map<String, List<SeniorQueryBean>> map = list.stream().collect(Collectors.groupingBy(SeniorQueryBean::getFieldName));
        for (Entry<String, List<SeniorQueryBean>> entry : map.entrySet()) {
            //排序，将与逻辑放在最前面
            List<SeniorQueryBean> mapList = entry.getValue().stream().sorted(Comparator.comparing(SeniorQueryBean::getLogicalValue)).collect(Collectors.toList());
            //拼接sql
            for (SeniorQueryBean seniorQueryBean : mapList) {
                if ("bh".equals(seniorQueryBean.getOperator())) {
                    seniorQueryBean.setOperator("like");
                    seniorQueryBean.setQueryValue(" concat('%'," + "'" + seniorQueryBean.getQueryValue() + "'" + ",'%')");
                } else {
                    seniorQueryBean.setQueryValue("'" + seniorQueryBean.getQueryValue() + "'");
                }
            }
            mapList.get(0).setFieldName("(" + mapList.get(0).getFieldName());
            mapList.get(mapList.size() - 1).setQueryValue(mapList.get(mapList.size() - 1).getQueryValue() + ")");
            //处理完的SeniorQueryBean依次放入flist
            for (SeniorQueryBean seniorQueryBean : mapList) {
                flist.add(seniorQueryBean);
            }
        }
        return flist;
    }

    public static List<String> queryChildrenArea(String parentId, String groupCode, BusinessAreaMapper mapper) {
        List<SelectBean> list = mapper.findBusinessAreaByParentId(parentId, groupCode);
        List<String> result = new ArrayList<>();
        if (list != null && list.size() > 0) {
            result.addAll(list.stream().map(SelectBean::getId).collect(Collectors.toList()));
        } else {
            result = null;
        }
        //result.add(list.str);
		/*for (SelectBean selectBean : list){
			List<String> sub = queryChildrenArea(selectBean.getId(),groupCode,mapper);
			result.addAll(sub);
		}*/
        return result;
    }
}
